import {
  indexApi
} from '../../../api/index';
import {
  request
} from '../../../utils/request';

import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
Page({
  data: {
    defaultData: {
      title: "按键面板", // 导航栏标题
      // imageSrc: "/images/back.png",
      isBackToPreviousPage: true
    },
    imageURL: "https://zntg.swehszn.com/file/WechatIMG637.png",
    sysDicKey: "SWITCH_MODEL",
    imageList: [],
    selectedImageUrl: "",
    selectedImageId: null,
    myImageList: [],
    isShow: false,
    isNewBuild: true,
    selectedImgPid: null,
    canvasHeight: 300,
    url: "",
    isSelect: true,
    isHide: false,
    aaa: 0
  },

  onLoad(options) {
    this.getSysDicSwitchModel()
    const imageList = wx.getStorageSync('imageList');
    const myImageList = wx.getStorageSync('myImageList');
    if (imageList !== undefined && myImageList !== undefined) {
      console.log('imageList:', imageList);
      console.log('myImageList:', myImageList);
      this.setData({
        imageList: imageList,
        myImageList: myImageList,
        selectedImageId: myImageList[0].id,
        selectedImageUrl: myImageList[0].newcode,
        selectedImgPid: myImageList[0].pid
      })
    }
  },

  onShow() {

  },



  async getSysDicSwitchModel() {
    try {
      const res = await request({
        url: indexApi.getSysDicSwitchModelApi(),
        data: {}
      });
      console.log("按键面板图片", res.data);

      const updatedImageList = res.data.map((item, index) => ({
        ...item,
        topLeftValue: '',
        topRightValue: '',
        bottomLeftValue: '',
        bottomRightValue: '',
        threeLeftValue: "",
        threeCenterValue: "",
        threeRightValue: "",
        sixLeftValue: "",
        sixCenterValue: "",
        sixRightValue: "",
        keyPanelNameValue: "",
        keyPanelNumValue: null,
        newcode: "",
        isSelect: false // 第一个图片的 isSelect 为 true
      }));

      // 设置数据
      this.setData({
        imageList: updatedImageList,
        // selectedImageUrl: updatedImageList[0].code,
        // selectedImageId: updatedImageList[0].id
      });

      console.log("图片", this.data.imageList);
    } catch (error) {
      console.error("Error:", error);
    }
  },



  // 选择我的图片
  selectImagePid(event) {
    const selectedPid = event.currentTarget.dataset.pid;
    const selectedImage = this.data.myImageList.find(item => item.pid == selectedPid);
    console.log("selectedImage", selectedImage);
    console.log("myImageList", this.data.myImageList);
    console.log("selectedPid", selectedPid);

    if (selectedImage) {
      const imageListIndex = this.data.imageList.findIndex(item => item.id == selectedImage.id);

      if (imageListIndex !== -1) {
        const updatedImageList = [...this.data.imageList];
        updatedImageList[imageListIndex] = selectedImage;

        this.setData({
          selectedImageId: selectedImage.id,
          selectedImageUrl: selectedImage.newcode,
          imageList: updatedImageList,
          selectedImgPid: selectedPid,
          isNewBuild: false,
        });

      } else {
        console.warn("未在 imageList 中找到匹配的 id:", selectedImage.id);
      }
    }
    console.log("selectedImgPid", this.data.selectedImgPid);
  },



  // 删除图片
  delImage() {
    const {
      myImageList,
      selectedImgPid,
      imageList,
      selectedImageId
    } = this.data;

    if (!selectedImgPid) {
      wx.showToast({
        title: '请选择要删除的图片',
        icon: 'none',
      });
      return;
    }

    Dialog.confirm({
      title: '删除提示',
      message: '确定删除该图片吗？',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(() => {
      // 用户点击了确认
      const selectedPid = myImageList.find(item => item.pid == selectedImgPid);
      const selectedId = imageList.find(item => item.id == selectedImageId);
      console.log("selectedPid", selectedPid);
      console.log("selectedId", selectedId);
      console.log("imageList", imageList);

      // 过滤掉选中的图片
      const updatedImageList = myImageList.filter(item => item.pid !== selectedImgPid);
      console.log("updatedImageList", updatedImageList);

      this.setData({
        myImageList: updatedImageList,
      });

      if (updatedImageList.length > 0) {
        this.setData({
          selectedImageId: updatedImageList[0].id,
          selectedImageUrl: updatedImageList[0].newcode,
          selectedImgPid: updatedImageList[0].pid
        });
      } else {
        this.setData({
          selectedImageId: null,
          selectedImageUrl: "",
          selectedImgPid: null
        });
      }


      wx.showToast({
        title: '图片已删除',
      });
      wx.setStorageSync('imageList', this.data.imageList);
      wx.setStorageSync('myImageList', this.data.myImageList);
      console.log("图片已删除, 更新后的 myImageList:", this.data.myImageList);
    }).catch(() => {
      // 用户点击了取消
      wx.showToast({
        title: '取消删除',
        icon: 'none'
      });
    });
  },

  // 全部删除图片
  allDelImage() {
    Dialog.confirm({
      title: '删除提示',
      message: '确定删除所有图片吗？',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    }).then(() => {
      // 用户点击了确认
      this.setData({
        myImageList: [], // 清空图片列表
        selectedImageId: null, // 重置选中的图片ID
        selectedImageUrl: "", // 重置选中的图片URL
        selectedImgPid: null // 重置选中的图片PID
      });

      // 同步清空本地存储（如果需要的话）
      wx.setStorageSync('imageList', []);
      wx.setStorageSync('myImageList', []);

      wx.showToast({
        title: '所有图片已删除',
      });
    }).catch(() => {
      // 用户点击了取消
      wx.showToast({
        title: '取消删除所有图片',
        icon: 'none'
      });
    });
  },


  // allMergeImage: function () {
  //   const imageUrls = this.data.myImageList.map(item => item.newcode);
  //   console.log("imageUrls", imageUrls);

  //   // Step 2: 绘制到canvas
  //   const imageCount = imageUrls.length;
  //   const imageHeight = 300;
  //   const totalHeight = imageHeight * imageCount;

  //   // Step 3: 创建canvas并设置动态高度
  //   const query = wx.createSelectorQuery();
  //   query.select('#imageCanvas')
  //     .node()
  //     .exec((res) => {
  //       console.log("res", res);
  //       const canvas = res[0].node;
  //       const ctx = canvas.getContext('2d');


  //       canvas.width = 300;
  //       canvas.height = totalHeight;

  //       let yOffset = 0;

  //       // 绘制每一张图片
  //       imageUrls.forEach((filePath, index) => {
  //         const img = canvas.createImage();
  //         img.src = filePath;
  //         console.log();

  //         img.onload = () => {
  //           ctx.drawImage(img, 0, yOffset, 300, 300);
  //           yOffset += imageHeight;

  //           // 如果所有图片都加载完毕，才生成合并后的图片
  //           if (index == imageUrls.length - 1) {
  //             this.setData({
  //               canvasHeight: totalHeight
  //             });

  //             // 生成合并后的图片
  //             wx.canvasToTempFilePath({
  //               canvas: canvas,
  //               success(res) {
  //                 console.log('合并后的图片路径:', res.tempFilePath);

  //                 // 预览
  //                 wx.previewImage({
  //                   current: res.tempFilePath,
  //                   urls: [res.tempFilePath]
  //                 });
  //               },
  //               fail(err) {
  //                 console.log('生成合并图片失败:', err);
  //               }
  //             });
  //           }
  //         };

  //         img.onerror = (err) => {
  //           console.log('图片加载失败:', err);
  //         };
  //       });
  //     });
  // },

  allMergeImage: function () {
    const imageUrls = this.data.myImageList.map(item => item.newcode);

    // 直接调用 wx.previewImage 方法，传入第一个图片的 URL 作为当前图片，以及所有图片的 URL 数组
    wx.previewImage({
      current: imageUrls[0], // 当前显示图片的 http 链接
      urls: imageUrls // 需要预览的图片 http 链接列表
    });
  },


  onImageClick(event) {
    console.log("event", event);
    const {
      imageList,
      myImageList
    } = this.data;

    const imageUrl = event.currentTarget.dataset.url; // 从 event 获取点击的图片 URL
    const imageId = event.currentTarget.dataset.id; // 从 event 获取点击的图片 ID

    // 更新选中的图片相关数据
    this.setData({
      selectedImageUrl: imageUrl,
      selectedImageId: imageId,
    });

    // 更新 imageList 中的 isSelect 值
    const updatedImageList = imageList.map(item => {
      return {
        ...item,
        isSelect: item.id == imageId // 选中的图片设为 true，其余设为 false
      };
    });

    // 更新数据
    this.setData({
      imageList: updatedImageList,
      isShow: true
    });

    this.newBuiltImage()
    this.generateImage()

    // console.log("updatedImageList", updatedImageList);

    // // 在 imageList 数组中找到对应的数据项
    // const selectedImage = updatedImageList.find(item => item.id == this.data.selectedImageId);
    // console.log("selectedImage", selectedImage);

    // // 判断是否需要生成新的图片
    // if (
    //   selectedImage.bottomLeftValue === "" &&
    //   selectedImage.bottomRightValue === "" &&
    //   selectedImage.threeCenterValue === "" &&
    //   selectedImage.threeLeftValue === "" &&
    //   selectedImage.threeRightValue === "" &&
    //   selectedImage.topLeftValue === "" &&
    //   selectedImage.topRightValue === "" &&
    //   selectedImage.keyPanelNameValue === "" &&
    //   selectedImage.keyPanelNumValue === null
    // ) {
    //   this.setData({
    //     isNewBuild: true,
    //     selectedImgPid: null,
    //   });
    // } else {
    //   this.setData({
    //     isNewBuild: false,
    //     selectedImgPid: selectedImage.pid,
    //   });
    // }

    console.log("imageList", this.data.imageList);
  },

  //隐藏面板
  hidePanel() {
    const updatedImageList = this.data.imageList.map(item => ({
      ...item,
      isSelect: false // 设置所有的 isSelect 为 false
    }));

    this.setData({
      isHide: !this.data.isHide,
      imageList: updatedImageList
    })
  },

  // 刻字
  onInput(event) {
    const corner = event.currentTarget.dataset.corner;
    let value = event.detail.value;
    console.log("value", value);
    console.log("corner", corner);

    // 限制输入最大字符数为4
    if (value.length > 4) {
      value = value.slice(0, 4); // 截取前4个字符
    }

    const selectedImageId = this.data.selectedImageId;
    const updatedImageList = this.data.imageList.map(item => {
      if (item.id == selectedImageId) {
        return {
          ...item,
          [`${corner}Value`]: value
        };
      }
      return item;
    });

    this.setData({
      imageList: updatedImageList
    });
    this.generateImage()

    console.log("更新后的 imageList", this.data.imageList);
    console.log("更新后的 myImageList", this.data.myImageList);
  },

  // 新建
  newBuiltImage() {
    const {
      selectedImageId,
      imageList
    } = this.data;

    // 在 imageList 数组中找到对应的数据项
    const selectedImage = imageList.find(item => item.id == selectedImageId);

    console.log("新建在 imageList 数组中找到对应的数据项", selectedImage);
    if (selectedImage) {
      console.log("找到对应的数据项", selectedImage);
      // 清空指定字段
      selectedImage.bottomLeftValue = '';
      selectedImage.bottomRightValue = '';
      selectedImage.threeCenterValue = '';
      selectedImage.threeLeftValue = '';
      selectedImage.threeRightValue = '';
      selectedImage.topLeftValue = '';
      selectedImage.topRightValue = '';

      selectedImage.sixLeftValue = '';
      selectedImage.sixCenterValue = '';
      selectedImage.sixRightValue = '';

      selectedImage.keyPanelNameValue = '';
      selectedImage.keyPanelNumValue = '';
      selectedImage.newcode = '';

    }
    console.log("新建在 imageList 数组中找到对应的数据项", selectedImage);
    this.setData({
      imageList,
      isNewBuild: true,
      selectedImgPid: null,
      isHide: false
    })

    console.log("新建========myImageList", this.data.myImageList);
  },

  //生成图片
  async generateImage() {
    const {
      selectedImageUrl,
      selectedImageId,
      imageList,
      isNewBuild,
      selectedImgPid
    } = this.data;
    console.log("========", imageList);

    // 找到选中的图片数据对象
    const selectedImage = imageList.find(item => item.id == selectedImageId);
    console.log("找到选中的图片数据对象", selectedImage);


    // 获取 canvas 组件并创建 2D 上下文
    const query = wx.createSelectorQuery();
    query.select('#imageCanvas')
      .node()
      .exec((res) => {
        const canvas = res[0].node;
        const ctx = canvas.getContext('2d');

        // 设置图片
        const img = canvas.createImage();

        const newSelectedImage = imageList.find(item => item.id == selectedImageId);
        img.src = newSelectedImage.code + '?t=' + new Date().getTime(); // 添加时间戳，确保每次加载不同的图片 URL

        console.log("绘制画布的图片", selectedImageUrl);
        img.onload = () => {
          // 使用图片的实际大小调整 canvas 大小
          canvas.width = img.width;
          canvas.height = img.height;
          console.log("使用图片的实际大小调整 canvas 大小");
          // 图片中心位置
          const centerX = img.width / 2;
          const centerY = img.height / 2;

          // 绘制图片
          ctx.drawImage(img, 0, 0, img.width, img.height);

          // 设置文字样式
          ctx.font = '35px HarmonyOS Sans SC';
          ctx.fillStyle = 'black';

          if (selectedImageId == 230 || selectedImageId == 228 || selectedImageId == 235) {
            if (selectedImage.threeLeftValue) {
              ctx.fillText(selectedImage.threeLeftValue, centerX - 245, centerY + 180); // 三位左下角
            }
            if (selectedImage.threeCenterValue) {
              ctx.fillText(selectedImage.threeCenterValue, centerX - 60, centerY + 180); // 三位中下角
            }
            if (selectedImage.threeRightValue) {
              ctx.fillText(selectedImage.threeRightValue, centerX + 125, centerY + 180); // 三位右下角
            }
            if (selectedImageId == 235) {
              if (selectedImage.sixLeftValue) {
                ctx.fillText(selectedImage.sixLeftValue, centerX - 245, centerY - 150); // 六位左上角
              }
              if (selectedImage.sixCenterValue) {
                ctx.fillText(selectedImage.sixCenterValue, centerX - 60, centerY - 150); // 六位中上角
              }
              if (selectedImage.sixRightValue) {
                ctx.fillText(selectedImage.sixRightValue, centerX + 125, centerY - 150); // 六位右上角
              }
            }
          } else if (selectedImageId == 236) {
            if (selectedImage.topLeftValue) {
              ctx.fillText(selectedImage.topLeftValue, centerX - 250, centerY - 200); // 左上角
            }
            if (selectedImage.topRightValue) {
              ctx.fillText(selectedImage.topRightValue, centerX + 120, centerY - 200); // 右上角
            }
            if (selectedImage.bottomLeftValue) {
              ctx.fillText(selectedImage.bottomLeftValue, centerX - 250, centerY + 220); // 左下角
            }
            if (selectedImage.bottomRightValue) {
              ctx.fillText(selectedImage.bottomRightValue, centerX + 120, centerY + 220); // 右下角
            }
          } else {
            // 绘制四个角的文字内容
            console.log("/ 绘制四个角的文字内容");
            if (selectedImage.topLeftValue) {
              ctx.fillText(selectedImage.topLeftValue, centerX - 200, centerY - 120); // 左上角
            }
            if (selectedImage.topRightValue) {
              ctx.fillText(selectedImage.topRightValue, centerX + 80, centerY - 120); // 右上角
            }
            if (selectedImage.bottomLeftValue) {
              ctx.fillText(selectedImage.bottomLeftValue, centerX - 200, centerY + 150); // 左下角
            }
            if (selectedImage.bottomRightValue) {
              ctx.fillText(selectedImage.bottomRightValue, centerX + 80, centerY + 150); // 右下角
            }
          }

          if (selectedImage.keyPanelNameValue) {
            ctx.fillText(selectedImage.keyPanelNameValue, centerX - 50, centerY - 320); //名称
          }
          if (selectedImage.keyPanelNumValue) {
            ctx.fillText(selectedImage.keyPanelNumValue, centerX - 50, centerY + 350); // 数量
          }

          // 导出图片并更新 `imageList` 中的对应图片地址
          wx.canvasToTempFilePath({
            canvas: canvas,
            success: (res) => {
              // 更新 imageList 中对应的图片地址
              const updatedImageList = imageList.map(item => {
                if (item.id == selectedImageId) {
                  const updatedItem = {
                    ...item,
                    isSelect: false,
                    newcode: res.tempFilePath,
                    ...(isNewBuild && {
                      pid: `${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
                    })
                  };
                  console.log("updatedItem", updatedItem);

                  if (isNewBuild == true) {
                    console.log("将更新后的对象加入 myImageList", updatedItem);
                    console.log("myImageList", this.data.myImageList);
                    const newUpdatedItem = JSON.parse(JSON.stringify(updatedItem));
                    this.setData({
                      myImageList: [...this.data.myImageList, newUpdatedItem],
                      selectedImgPid: updatedItem.pid,
                      selectedImageId: updatedItem.id,
                      selectedImageUrl: updatedItem.newcode,
                    });
                    // wx.showToast({
                    //   title: '图片生成成功',
                    //   icon: 'none'
                    // });
                  } else {
                    console.log("是不是更新", isNewBuild);

                    const myImageList = [...this.data.myImageList];
                    const newUpdatedItem1 = JSON.parse(JSON.stringify(updatedItem));

                    // 根据 selectedImgPid 找到对应的索引
                    const index = myImageList.findIndex(item => item.pid === selectedImgPid);
                    if (index !== -1) {
                      // 替换对应的项
                      myImageList[index] = newUpdatedItem1;
                      this.setData({
                        myImageList,
                        selectedImageId: newUpdatedItem1.id,
                        selectedImageUrl: newUpdatedItem1.newcode
                      });
                    } else {
                      console.warn("未找到对应的 selectedImgPid 数据，无法更新！");
                    }
                    // wx.showToast({
                    //   title: '图片更新成功',
                    //   icon: 'none'
                    // });
                  }

                  console.log("========myImageList", this.data.myImageList);
                  // 返回更新后的对象
                  return updatedItem;
                }

                return item;
              });

              console.log("updatedImageList", updatedImageList);
              console.log("myImageList", this.data.myImageList);

              // 更新 imageList 到数据
              this.setData({
                imageList: updatedImageList,
                isNewBuild: false,
              });
              wx.setStorageSync('imageList', this.data.imageList);
              wx.setStorageSync('myImageList', this.data.myImageList);
              console.log("图片生成成功", this.data.selectedImageUrl);
            },
            fail: (error) => {
              console.error("生成图片失败：", error);
            }
          });

        };
      });
  },


  // 点击图片预览
  previewImage: function (e) {
    const currentUrl = e.currentTarget.dataset.src; // 当前图片的 URL
    console.log('当前图片 URL:', currentUrl);

    wx.previewImage({
      current: currentUrl, // 当前显示的图片 URL
      urls: [currentUrl], // 只包含当前图片
    });
  }

})